package com.handu.luna.boss.controller;

import java.util.LinkedList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import com.handu.luna.core.domain.BossException;
import com.handu.luna.core.domain.Mall;
import com.handu.luna.core.domain.goods.Category;
import com.handu.luna.core.domain.goods.Goods;


@Controller
@RequestMapping("/goods/category/*")
public class CategoryController extends BaseController {
 
	 
	@RequestMapping()
	public BossModel index(){
		
		Mall mall=new Mall();	
		mall.init();
		List<Category> list = mall.getAllCategories();
		for (Category category : list) {
			category.init(category.getId(),false);
		}

		return createModel().add("categorys",list).add("attributeList",context.getAttributeRepository().findAll());
	}
	
	@RequestMapping(value="add")
	public BossModel add(){
		LinkedList <Category> list =new LinkedList<Category>(   context.getCategoryRepository().getDisplayList());
		list.add(0,new Category(0,"顶级分类"));
		Category category = new Category();
		 
		category.setDisplayed(true);
		category.setNavigation(true);
		//属性
		
		return createModel("goods/category/save")
				.add("cateParents",list)
				.add("category",category)
				.add("attributeList",context.getAttributeRepository().findAll());
	}
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){ 
		LinkedList<Category> list = new LinkedList<Category>( context.getCategoryRepository().getDisplayList());
		list.add(0,new Category(0,"顶级分类"));
		Category cate = new Category().findOne(id); 
		//属性
		return createModel("goods/category/save").add("category",cate).add("cateParents",list).add("attributeList",context.getAttributeRepository().findAll());
	}
	
	 
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(long id){ 
        /*boolean flag = false;
		if(beforeDelete(id, flag)){
			throw new BossException("顶级分类不可移除，或者该分类下存在商品！");
		}*/
		
		List<Category> getIncludeParent = context.getCategoryRepository().getAllByCatIdNew(String.valueOf(id));
		List<Goods> goods = context.getGoodsRepository().findAll(id) ;//如果父类下没有商品，但是子分类下有商品，当删除父类的时候，也不允许删除！
	   
		if(!getIncludeParent.isEmpty()){
			throw new BossException("该分类下存在子分类，不可以将其移除!");   //顶级分类不可移除，或者该分类下存在商品！
		}else if(!goods.isEmpty()){
			throw new BossException("该分类下存在商品，不可以将其移除!"); 
		}else{
			context.getCategoryRepository().delete(id);
		}

		Mall mall=new Mall();	
		mall.init();
		List<Category> list = mall.getAllCategories();
		for (Category category : list) {
			category.init(category.getId(),false);
		}
		return createModel("goods/category/categorys_table").add("categorys",list);
	
	}
	
	
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid final Category category, final BindingResult bindingResult, RedirectAttributes redirectAttributes){
		String message = "";
		LinkedList <Category> list =new LinkedList<Category>(context.getCategoryRepository().getDisplayList());
		list.add(0,new Category(0,"顶级分类"));
		if (bindingResult.hasErrors()) {				
			return createModel("goods/category/save").add("cateParents",list);
		}
		//同级名称不能重复
		//List<Category> CategoryNameCheck;
		if(category.getId() == null)   //添加
		{ 	
			if(category.getParentId()!=0){
	 		//获得所父类的  子子孙孙
			List<Category> getIncludeParent = context.getCategoryRepository().getAllByCatIdNew(String.valueOf(category.getParentId()));
			for (Category lists : getIncludeParent) {
				if(lists.getName().equals(category.getName()) &&(lists.getParentId()==category.getParentId())){
					message = "所添加的商品分类名称：" + category.getName()+ "在同级分类下已存在";
					bindingResult.addError(new FieldError("category", "name", message));
					return createModel("goods/category/save").add("cateParents",list).add("attributeList",context.getAttributeRepository().findAll());
				}
			  }
			}else{
				List<Category> topCats = context.getCategoryRepository().getAllByCatId(category.getParentId());
				for (Category lists : topCats) {
					if(category.getName().equals(lists.getName()) && (lists.getParentId()==category.getParentId())){
						message = "所添加的商品分类名称：" + category.getName()+ "在同级分类下已存在";
						bindingResult.addError(new FieldError("category", "name", message));
						return createModel("goods/category/save").add("cateParents",list).add("attributeList",context.getAttributeRepository().findAll());
					}
				}
			}
			
			
		}else{		//修改
			//Category CategoryNameCheckById = context.getCategoryRepository().findOne(category.getParentId());
			Category oneinfo = context.getCategoryRepository().findOne(category.getId());
			if(category.getParentId()!=0){
			//获得所父类的  子子孙孙
			List<Category> getIncludeParent = context.getCategoryRepository().getAllByCatIdNew(String.valueOf(category.getParentId()));
			for (Category lists : getIncludeParent) {
				if(lists.getName().equals(category.getName()) && (lists.getId()!=category.getId()) &&(lists.getParentId()==category.getParentId())){
					message = "所修改的商品分类名称：" + category.getName()+ "在同级分类下已存在";
					bindingResult.addError(new FieldError("category", "name", message));
					return createModel("goods/category/save").add("cateParents",list).add("attributeList",context.getAttributeRepository().findAll());
				}
			  }
			}else{
				List<Category> topCats = context.getCategoryRepository().getAllByCatId(category.getParentId());
				for (Category lists : topCats) {
					if(category.getName().equals(lists.getName()) && (lists.getId()!=category.getId()) &&(lists.getParentId()==category.getParentId())){
						message = "所修改的商品分类名称：" + category.getName()+ "在同级分类下已存在";
						bindingResult.addError(new FieldError("category", "name", message));
						return createModel("goods/category/save").add("cateParents",list).add("attributeList",context.getAttributeRepository().findAll());
					}
				}
			}
			
			if(oneinfo.getParentId()==0 && category.getParentId()!=0){
				 
				bindingResult.addError(new FieldError("category", "parentId", "顶级目录不可以修改"));
				return createModel("goods/category/save").add("cateParents",list);
			}
		/*	else if(oneinfo.getName().equals(category.getName())){//else if(category.getParentId() != 0 && CategoryNameCheckById.getName().equals(category.getName())){如果新添加的分类名称与所选的分类名称相同，则不允许添加
				message = "分类名称：" + category.getName()+ "在同级下已存在";
				bindingResult.addError(new FieldError("category", "name", message));
				return createModel("goods/category/save").add("cateParents",list);
			}*/
			else if(checkOnChange(category.getId(),category.getParentId())){
				message = "父类不能修改成自己的子类！";
				bindingResult.addError(new FieldError("category", "name", message));
				return createModel("goods/category/save").add("cateParents",list);
			}else if(category.getId()==category.getParentId()){  
				message = "不能选择本身的分类！";
				bindingResult.addError(new FieldError("category", "name", message));
				return createModel("goods/category/save").add("cateParents",list);
			}
			/*else{
				message = "顶级分类不可修改，或者该分类下存在商品！";
				bindingResult.addError(new FieldError("category", "name", message));
				return createModel("goods/category/save").add("cateParents",list);
			}*/
		}
		
		
		if(null==category.getId()){
			message = "添加"+category.getName() + "成功";
			Category getParentCollectionByCatId = context.getCategoryRepository().findOne(category.getParentId());
			if(getParentCollectionByCatId!=null){
				if(getParentCollectionByCatId.getParentCollection()!=""){
					category.setParentCollection(getParentCollectionByCatId.getParentCollection() + "," + getParentCollectionByCatId.getId());	
				}else{
					category.setParentCollection(String.valueOf(getParentCollectionByCatId.getId()));	
				}
				
			}else{
				category.setParentCollection("");
			}
			category.save(category);
		}else{
			message = "修改"+category.getName() + "成功";
			//获得被选分类的  “parentCollection”
			Category getSelectCategoryParentCollection = context.getCategoryRepository().findOne(category.getParentId());
			if(getSelectCategoryParentCollection!=null){
				if(getSelectCategoryParentCollection.getParentCollection()==""){
					//category.setParentCollection(getSelectCategoryParentCollection.getParentCollection() + category.getParentId());
					category.setParentCollection(String.valueOf(getSelectCategoryParentCollection.getId()));
				}else{
					category.setParentCollection(getSelectCategoryParentCollection.getParentCollection() + ","+ getSelectCategoryParentCollection.getId());
				}
			}else{
				category.setParentCollection("");
			}
			
			
			Category oneinfo = context.getCategoryRepository().findOne(category.getId());
			if(oneinfo.getParentId()!=0 && category.getParentId()!=0){
				if(!replaceChildParentCollection(category.getId() , category.getParentId())){
					message = "编辑分类失败！";
				}
			}
			
			category.save(category);
		}
		//category.save(category);
		
		redirectAttributes.addFlashAttribute("message", message);
		return createModel("redirect:index");
	}
	
 
	//删除判断
/*	public boolean beforeDelete(long id,boolean flag){
		long num = context.getGoodsRepository().getNumByCatId(id) ;
		if(num!=0 || id==0){
			flag = true;
		}
		if(flag){
			
			return flag;
		}
		
		List<Category> childs = context.getCategoryRepository().getAllByCatId(id);  //判断该分类下有没有子分类
		if(!childs.isEmpty()){
			flag = true;
		}else{
			List<Goods> goodsList = context.getGoodsRepository().findAll(id); //context.getGoodsRepository().findAll(category.getId()) ;//如果父类下没有商品，但是子分类下有商品，当删除父类的时候，也不允许删除！
		    if(!goodsList.isEmpty()){
		    	flag = true;
		    }
		}
		
		if(childs.size()>0){
			for (Category category : childs) {
				if(category.getId()!=0){
					List<Goods> goodsList = context.getGoodsRepository().findAll(category.getId()); //context.getGoodsRepository().findAll(category.getId()) ;//如果父类下没有商品，但是子分类下有商品，当删除父类的时候，也不允许删除！
				    if(!goodsList.isEmpty()){
				    	flag = true;
				    }
				}else{
				   beforeDelete(category.getId(), flag);
				}
			}
		}	
		return flag;
		
	}*/
	
	
	//编辑分类的判断
	@RequestMapping(value="check")
	public @ResponseBody boolean check(long id , long selectedId){
		return checkOnChange(id,selectedId);
	}
	
	public boolean checkOnChange(long id , long selectedId){
		
		List<Category> childs = context.getCategoryRepository().getAllByCatId(id);
		
		if(childs.size()>0){
			for (Category category : childs) {
				if(category.getId() == selectedId){
					return true;
				}
			}
		}
		
		
		if(childs.size() >0){
			for (Category category : childs) {
				if(checkOnChange(category.getId(), selectedId)){
					return true;
				}
			}
		}		
		return false;
	}
	
	
	//循环替换孩子的“parentCollection”   new
		public boolean replaceChildParentCollection(long id , long pId){
			
		//获得所移动分类的  子子孙孙
		List<Category> getIncludeParent = context.getCategoryRepository().getAllByCatIdNew(String.valueOf(id));
		//获得所移动分类的“parentCollection”
		Category replaceChildParentCollection = context.getCategoryRepository().findOne(id);
		//获得被选择分类的 “parentCollection”
		Category selectCatParentCollection = context.getCategoryRepository().findOne(pId);
		if(selectCatParentCollection.getParentCollection()!=""){
			replaceChildParentCollection.setParentCollection(selectCatParentCollection.getParentCollection() + "," +selectCatParentCollection.getId());
		}else{
			replaceChildParentCollection.setParentCollection(String.valueOf(selectCatParentCollection.getId()));
		}
		
		
		for (Category list : getIncludeParent) {   //循环孩子，将孩子的“parentCollection”  
			if(replaceChildParentCollection.getParentCollection()==""){
				list.setParentCollection(String.valueOf(replaceChildParentCollection.getId()));
			}else{
				list.setParentCollection(replaceChildParentCollection.getParentCollection() + ","+ replaceChildParentCollection.getId());//list.getParentId()
			}
			
			
			if(replaceChildParentCollection(list.getId() , list.getParentId())){
				list.setParentCollection(list.getParentCollection());
				context.getCategoryRepository().save(list);
				return true;
			}	
		}
		
		return true;

		}
	
 
	
}
